import Radio from 'backbone.radio';
import Mn from 'backbone.marionette';
import { hideLoader, showLoader } from '../../tools';
import EntryModel from '../models/EntryModel';


const Controller = Mn.Object.extend({
    initialize(options){
        this.facade = Radio.channel('facade');
        this.config = Radio.channel('config');
        this.app = Radio.channel('app');
        console.log("Controller.initialize");
        this.rootView = options['rootView'];
        this.productDefaults = this.config.request('get:options', 'defaults');
    },
    index(){
        console.log("Controller.index");
        this.rootView.index();
    },
    showModal(view){
        this.rootView.showModal(view);
    },
    editEntry(entryId){
        const model = this.facade.request('get:entry', entryId);
        showLoader();
        const promise = this.facade.request('load:criteria', model);
        promise.then(
            (collection) => {hideLoader(); this.rootView.entryEdit(model, collection);}
        )
    },
    addEntry(){
        const collection = this.facade.request('get:collection', 'entries');
        const model = new EntryModel();
        this.rootView.entryAdd(model, collection);
    },
    editEntryMainData(modelId){
        const collection = this.facade.request('get:collection', 'entries');
        const model = collection.get(modelId)
        this.rootView.entryEditMainData(model, collection);
    },
    showEntryExport(model){
        const url = model.exportUrl();
        window.openPopup(url);
    },
    showEntryDuplicate(model){
        this.rootView.showEntryDuplicateForm(model);
    },
    // Common model views
    _onModelDeleteSuccess: function(){
        let messagebus = Radio.channel('message');
        messagebus.trigger('success', this, "Vos données ont bien été supprimées");
        this.app.trigger('navigate', 'index');
    },
    _onModelDeleteError: function(){
        let messagebus = Radio.channel('message');
        messagebus.trigger('error', this,
                           "Une erreur a été rencontrée lors de la " +
                           "suppression de cet élément");
    },
    modelDelete(childView){
        console.log("Controller.modelDelete");
        var result = window.confirm("Êtes-vous sûr de vouloir supprimer cet élément ?");
        if (result){
            childView.model.destroy(
                {
                    success: this._onModelDeleteSuccess.bind(this),
                    error: this._onModelDeleteError.bind(this),
                    wait: true
                }
            );
        }
    },
});
export default Controller;
